package juc_14_ForkJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

public class ForkJoinDemo01 extends RecursiveTask<Long> {
    private Long start;
    private Long end;
    private Long temp = 1_0000_0000L;

    public ForkJoinDemo01(Long start, Long end) {
        this.start = start;
        this.end = end+1;
    }

    @Override
    public Long compute() {
        if ((end - start < temp)) {
            Long sum = 0L;
            for (Long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        } else {
            // System.out.println("准备拆分任务..." + Thread.currentThread().getName() + " -> " + start + " : " + end);
            Long middle = (start + end) / 2;
            ForkJoinDemo01 task01 = new ForkJoinDemo01(start, middle);
            task01.fork();
            ForkJoinDemo01 task02 = new ForkJoinDemo01(middle+1, end);
            task02.fork();

            Long result = task01.join() + task02.join();
            return result;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Long start = 0L;
        Long end = 1_0000_0000L;


        long start1 = System.currentTimeMillis();

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinDemo01 task = new ForkJoinDemo01(start, end);

//        pool.execute(task);
//        System.out.println(task.get());

        ForkJoinTask<Long> submit = pool.submit(task);
        System.out.println(submit.get());

        long end1 = System.currentTimeMillis();
        System.out.println(end1-start1);

        long start2 = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(start, end).parallel().reduce(0, Long::sum);
        System.out.println(sum);
        long end2 = System.currentTimeMillis();
        System.out.println(end2-start2);
    }
}
